﻿using System;
using Samurai.Client.DataContexts;
using Samurai.DAL;
using Samurai.Infrastructure;
using System.Collections.ObjectModel;
using System.Windows.Forms;

namespace Samurai.Client.Commands
{
    public class RefreshMoviesCommand : CommandBase
    {
        private readonly ObservableCollection<Movie> _movies;
        private readonly ObservableCollection<GenreItem> _genres;

        public RefreshMoviesCommand(ObservableCollection<Movie> movies, ObservableCollection<GenreItem> genres)
        {
            _movies = movies;
            _genres = genres;
        }

        protected override void InvokeExecute(object parameter)
        {
            if (LongOperationStarted != null)
                LongOperationStarted();

            Movie[] movies = null;
            GenreItem[] genres = null;

            System.Windows.Application.Current.Dispatcher.Invoke(
                new Action(
                    () =>
                    {
                        movies = Manager.Instance.GetNewValidMovies(_movies);
                        genres = Manager.Instance.GetNewGenres(_genres);
                    }
                    )
                );

            foreach (var movie in movies)
            {
                _movies.Add(movie);
                Application.DoEvents();
            }

            _genres.Add(MoviesDataContext.AllItem);
            foreach (var genre in genres)
            {
                _genres.Add(genre);
                Application.DoEvents();
            }

            if (LongOperationFinished != null)
                LongOperationFinished();
        }
    }
}
